package com.guava.mall.tool.common.utils;

import cn.hutool.core.util.StrUtil;
import com.guava.mall.tool.common.exception.IllegalParamException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * @Author: DengYunHu
 * @Date: 2020/12/12 16:40
 */
public class ValidationUtils {

    public static void valid(boolean valid, String errorMsg, Object... formatParam) {
        if (valid) {
            throw new IllegalParamException(StrUtil.format(errorMsg,formatParam));
        }
    }

    public static void anyNull(String errorMsg, Object... params) {
        if (hasNull(params)) {
            throw new IllegalParamException(errorMsg);
        }
    }

    public static void checkBindingResult(BindingResult bindingResult){
        boolean hasErrors = bindingResult.hasErrors();
        if (hasErrors){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                throw new IllegalParamException(fieldError.getDefaultMessage());
            }
        }
    }

    public static boolean hasNull(Object... params){
        return Stream.of(params).anyMatch(Objects::isNull);
    }
}
